<?php
/**
 * 文件下载
 */
namespace  App\Http\Services;
class DownloadService
{

    /**
     * 打包下载文件
     *
     * @param array $paths 文件集合，包括原文件名及文件存储路径[['name' => 'file_name', 'path' => 'file_paht']]
     * @param [type] $name
     * @return void
     */
    public function downloadZip($files)
    {
//        var_dump($files);exit;
        $tempZipName = 'uploads/' . uniqid() . '.zip';
        touch($tempZipName);
        $zip = new \ZipArchive();

        if ($zip->open($tempZipName) !== true) {
            $this->error = ERROR_MES;
            return false;
        }

        foreach($files as $file) {
            $zip->addFile($file['path'], $file['name']);
        }

        $zip->close();
        $this->download($tempZipName, date('YmdHis', time()) . '.zip');
        unlink($tempZipName);
    }

    /**
     * http 文件下载，下载完成后删除文件
     *
     * @param  string $path  文件真实路径
     * @param  string $name 文件重命名
     */
    public function download($path, $name)
    {
        $finfo = new \finfo(FILEINFO_MIME);
        $type = $finfo->file($path);

        $httpUserAgent = $_SERVER['HTTP_USER_AGENT'];
        header("Pragma: public");
        header("Cache-control: max-age=0");
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header("Expires: " . gmdate("D, d M Y H:i:s", time()) . "GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT");

        if (strpos($httpUserAgent, 'MSIE') !== false || strpos($httpUserAgent, 'rv:11.0')) {
            $encodedFilename = urlencode($name);
            $encodedFilename = str_replace("+", "%20", $encodedFilename);
            header("Content-Disposition: attachment; filename=" . $encodedFilename);
        } elseif (strpos($httpUserAgent, 'FireFox') !== false) {
            header("Content-Disposition: attachment; filename*=\"utf8''" . $name . '"');
        } else {
            header("Content-Disposition: attachment; filename=\"$name\"");
        }

        header("Content-Length: " . filesize($path));
        header("Content-Type: " . $type);
        header('Content-Encoding: none');
        header("Content-Transfer-Encoding: binary");

        $stream = fopen($path, 'r');
        while (!feof($stream)) {
            echo fread($stream, 1024);
        }
        fclose($stream);

        // 直接输入并结束请求
        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        }

        return true;
    }
}